package com.ruoyi.socket.controller;

import java.util.Date;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.ruoyi.socket.domain.ChatRecords;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.socket.domain.TbAnswer;
import com.ruoyi.socket.service.ITbAnswerService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 自动问答Controller
 * 
 * @author ruoyi
 * @date 2023-05-05
 */
@RestController
@RequestMapping("/answer")
public class TbAnswerController extends BaseController
{
    @Autowired
    private ITbAnswerService tbAnswerService;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询自动问答列表
     */
    @RequiresPermissions("answer:answer:list")
    @GetMapping("/list")
    public TableDataInfo list(TbAnswer tbAnswer)
    {
        startPage();
        List<TbAnswer> list = tbAnswerService.selectTbAnswerList(tbAnswer);
        return getDataTable(list);
    }

    /**
     * 导出自动问答列表
     */
    @RequiresPermissions("answer:answer:export")
    @Log(title = "自动问答", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbAnswer tbAnswer)
    {
        List<TbAnswer> list = tbAnswerService.selectTbAnswerList(tbAnswer);
        ExcelUtil<TbAnswer> util = new ExcelUtil<TbAnswer>(TbAnswer.class);
        util.exportExcel(response, list, "自动问答数据");
    }

    /**
     * 获取自动问答详细信息
     */
    @RequiresPermissions("answer:answer:query")
    @GetMapping(value = "/{answerId}")
    public AjaxResult getInfo(@PathVariable("answerId") Long answerId)
    {
        return success(tbAnswerService.selectTbAnswerByAnswerId(answerId));
    }

    /**
     * 新增自动问答
     */
    @Log(title = "自动问答", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbAnswer tbAnswer)
    {
        return toAjax(tbAnswerService.insertTbAnswer(tbAnswer));
    }

    /**
     * 修改自动问答
     */
    @Log(title = "自动问答", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbAnswer tbAnswer)
    {
        return toAjax(tbAnswerService.updateTbAnswer(tbAnswer));
    }

    /**
     * 删除自动问答
     */
    @Log(title = "自动问答", businessType = BusinessType.DELETE)
	@DeleteMapping("/{answerIds}")
    public AjaxResult remove(@PathVariable Long[] answerIds)
    {
        return toAjax(tbAnswerService.deleteTbAnswerByAnswerIds(answerIds));
    }



    /**
     * 查询自动问答列表
     */
    @GetMapping("/getMessage")
    public AjaxResult getMessage(){
        return AjaxResult.success("这里是人工客服,请问你有什么问题吗?");

    }

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @GetMapping("/sendMessageEs/{username}/{message}")
    public AjaxResult sendMessage(@PathVariable String username,@PathVariable String message) throws IOException {
        //用户发送内容记录到MongoDB中
        ChatRecords records = new ChatRecords();
        records.setContent(message);
        records.setUsername(username);
        records.setCreateTime(new Date());
        mongoTemplate.save(records);



        //根据message的数据,查询es的常见问题,返回
        SearchRequest searchRequest = new SearchRequest("answer");
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        queryBuilder.must(QueryBuilders.matchQuery("antistop", message));
        searchRequest.source().query(queryBuilder);
        SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        String result="";
        if(hits.length==0){

            result="您的消息已经收到,请等待客服联系";
        }else{
            for (int i=0;i<hits.length;i++){
                String sourceAsString = hits[i].getSourceAsString();
                TbAnswer answer = JSON.parseObject(sourceAsString, TbAnswer.class);
                result+=(i+1)+":"+ answer.getAnswerResult()+"<br/>";

            }
        }



        return AjaxResult.success(result);

    }


}
